package wiki.zimo.domain;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @version v1.0
 * @auther: 子墨
 * @datetime: 2018/11/4 22:10
 * @description: 购物车实体类
 */
public class Cart {
    private Map<String, CartItem> cart = new HashMap<>();// 购物项集合
    private double total = 0.0d;// 购物车总金额

    public Map<String, CartItem> getCart() {
        return cart;
    }

    public void setCart(Map<String, CartItem> cart) {
        this.cart = cart;
    }

    public double getTotal() {
        return total;
    }

    public void setTotal(double total) {
        this.total = total;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Cart cart1 = (Cart) o;
        return Double.compare(cart1.total, total) == 0 &&
                Objects.equals(cart, cart1.cart);
    }

    @Override
    public int hashCode() {

        return Objects.hash(cart, total);
    }

    @Override
    public String toString() {
        return "Cart{" +
                "cart=" + cart +
                ", total=" + total +
                '}';
    }

    /**
     * @auther: 子墨
     * @date: 2018/11/4 22:19
     * @describe: 添加购物项到购物车中
     * @param: [item]
     * @return: void
     * @version v1.0
     */
    public void addCartItemToCart(CartItem item) {
        String pid = item.getProduct().getPid();
        if (cart.containsKey(pid)) {
            CartItem oldItem = cart.get(pid);
            oldItem.setCount(oldItem.getCount() + item.getCount());
        } else {
            cart.put(pid, item);
        }
        total += item.getSubTotal();
    }

    /**
     * @auther: 子墨
     * @date: 2018/11/4 22:21
     * @describe: 从购物车中移除商品
     * @param: [item]
     * @return: void
     * @version v1.0
     */
    public void removeProductFromCart(String pid) {
        if (cart.containsKey(pid)) {
            CartItem item = cart.remove(pid);
            total -= item.getSubTotal();
        }
    }

    /**
     * @auther: 子墨
     * @date: 2018/11/4 22:23
     * @describe: 清空购物车
     * @param: []
     * @return: void
     * @version v1.0
     */
    public void clearCart() {
        cart.clear();
        total = 0.0d;
    }

    /**
     * @auther: 子墨
     * @date: 2018/11/4 22:24
     * @describe: 获取购物车中所有的购物项
     * @param: []
     * @return: java.util.Collection<wiki.zimo.domain.CartItem>
     * @version v1.0
     */
    public Collection<CartItem> getCartItems() {
        return cart.values();
    }
}
